# account.py
from django.shortcuts import render, redirect
from app01.utilss.BootStrapModelform import BootStrapForm
from django import forms
from django.views.decorators.cache import never_cache
from app01 import models
from app01.utilss.secery import md5

class LoginForm(BootStrapForm):
    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(render_value=True)
    )
    captcha = forms.CharField(
        label='验证码',
        widget=forms.TextInput
    )

    def __init__(self, *args, **kwargs):
        # 自定义构造函数，接收 request 参数
        self.request = kwargs.pop('request', None)  # 弹出 request 参数并存储
        super().__init__(*args, **kwargs)  # 调用父类构造函数

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)

    def clean_captcha(self):
        if not self.request:  # 检查 request 是否存在
            raise forms.ValidationError('请求对象缺失，请联系管理员')
        captcha = self.cleaned_data.get('captcha')
        session_captcha = self.request.session.get('captcha_text', '')
        print(f'User input captcha: {captcha}')
        print(f'Session captcha: {session_captcha}')
        if not session_captcha:
            raise forms.ValidationError('验证码已过期，请刷新页面重试')
        if captcha.upper() != session_captcha.upper():
            raise forms.ValidationError('验证码错误')
        return captcha

def login_view(request):
    """改进版登录视图"""
    if request.method == 'GET':
        form = LoginForm(request=request)  # 传递 request 对象
        return render(request, 'login.html', {'form': form})
    form = LoginForm(data=request.POST, request=request)  # 传递 request 对象
    if form.is_valid():
        # 验证成功
        admin_obj = models.Admin.objects.filter(
            username=form.cleaned_data.get('username'),
            password=form.cleaned_data.get('password')
        ).first()
        if not admin_obj:
            form.add_error('password', '用户名或密码错误')
            return render(request, 'login.html', {'form': form})
        request.session['info'] = {'id': admin_obj.id, 'username': admin_obj.username}
        return redirect('/admin/list/')
    else:
        # 验证失败
        return render(request, 'login.html', {'form': form})

@never_cache
def logout(request):
    """注销"""
    request.session.clear()
    return redirect('/login/')
